<template>
  <!-- 故障类别分析 -->
  <a-spin :spinning="loading">
    <div class="failureAnalysis">
      <div class="titleBar">
        <div class="title">
          故障类别分析
          <div class="dateRange">
            <a-range-picker
              v-model:value="dateRange"
              size="small"
              :allowClear="false"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="margin-right: 8px"
            />
            <a-button
              size="small"
              type="primary"
              class="queryBtn"
              @click="outageDashboardData"
              >查询</a-button
            >
            <a-button size="small" type="link" @click="handleReset"
              >重置</a-button
            >
          </div>
        </div>
      </div>
      <!-- 环形图 -->
      <div class="circleCharts">
        <template v-if="chartData.length > 0">
          <div
            class="chartItem"
            v-for="(item, index) in chartData"
            :key="item.faultType"
            :class="{ active: currentFaultType === item.faultType }"
            @click="handleChartItemClick(item.faultType, index)"
          >
            <div
              class="chartContainer"
              :ref="(el) => setChartRef(el, index)"
            ></div>
            <div class="chartTitle">{{ item.faultType }}</div>
            <div class="chartValue">{{ item.ratio }}</div>
          </div>
        </template>
        <template v-else>
          <div class="noData">
            <div class="noDataText">暂无数据</div>
          </div>
        </template>
      </div>
      <div class="barChartContainer">
        <template v-if="chartData.length > 0">
          <div ref="barChartRef" class="chartInstance"></div>
        </template>
        <template v-else>
          <div class="noData">
            <div class="noDataText">暂无数据</div>
          </div>
        </template>
      </div>
    </div>
  </a-spin>
</template>

<script setup>

import * as echarts from "echarts";
import dayjs from "dayjs";
const props = defineProps({
  pageType: {
    type: String,
  },
});
const $api = inject("$api");
const getDefaultDateRange = () => {
  // 默认选上月的1号到上月的最后一天
  const end = dayjs().subtract(1, "month").endOf("month");
  const start = dayjs().subtract(1, "month").startOf("month");
  return [start.format("YYYY-MM-DD"), end.format("YYYY-MM-DD")];
};
const dateRange = ref(getDefaultDateRange());
const chartData = ref([]);

// 动态环形图引用数组
const chartRefs = ref([]);
const setChartRef = (el, index) => {
  if (el) {
    chartRefs.value[index] = el;
  }
};

// 添加柱状图的引用
const barChartRef = ref(null);

// 图表实例数组
const circleCharts = ref([]);
let barChart = null;

const currentFaultType = ref("");

const updateBarChart = (faultType) => {
  if (!barChart) return;
  let option;
  if (faultType === "用户停电") {
    // 用户停电的特殊柱线混合图配置
    const userPowerOutageData = chartData.value.find(
      (item) => item.faultType === "用户停电"
    );
    const categories = []; // 所有电站名称
    const repairTimeData = []; // 所有faultFixTime数据
    const stationDowntimeData = []; // 所有ShutdownNum数据
    const affectedChargeData = []; // 所有affectNum数据
    if (userPowerOutageData && userPowerOutageData.userChildDtoList) {
      userPowerOutageData.userChildDtoList.forEach((station) => {
        categories.push(station.stationName);
        repairTimeData.push(Number(station.faultFixTime));
        stationDowntimeData.push(station.causeProjectShutdownNum);
        affectedChargeData.push(station.affectNum);
      });
    }

    const total = repairTimeData.length || 0;

    option = {
      title: [
        {
          text: "用户停电-故障相关统计",
          left: "5%",
          top: "3%",
          textStyle: {
            color: "#e2e8f0",
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        {
          text: `用户停电记录总数: ${total}个`,
          right: "5%",
          top: "3%",
          textStyle: {
            color: "#94a3b8",
            fontSize: 12,
          },
        },
      ],
      legend: {
        data: ["故障修复时间", "电站停运次数", "影响充放次数"],
        top: "13%",
        right: "15%",
        textStyle: {
          color: "#94a3b8",
        },
        itemWidth: 10,
        itemHeight: 10,
      },
      grid: {
        left: "5%",
        right: "5%",
        bottom: "5%",
        top: "25%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: categories,
        axisLine: {
          lineStyle: {
            color: "#475569",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: "#94a3b8",
          interval: 0,
          rotate: 0,
          fontSize: 12,
          margin: 10,
        },
      },
      yAxis: [
        {
          type: "value",
          name: "",
          min: 0,
          max: 25,
          interval: 5,
          axisLabel: {
            color: "#94a3b8",
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#475569",
            },
          },
          splitLine: {
            lineStyle: {
              color: "#334155",
              type: "dotted",
            },
          },
        },
        {
          type: "value",
          name: "",
          min: 0,
          max: 5,
          interval: 1,
          axisLabel: {
            color: "#94a3b8",
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#475569",
            },
          },
          splitLine: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: "故障修复时间",
          type: "bar",
          barWidth: "20",
          barGap: "10",
          yAxisIndex: 0,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#5A8DFF" },
              { offset: 1, color: "#2A5FFF" },
            ]),
            borderRadius: [4, 4, 0, 0],
          },
          showBackground: true,
          backgroundStyle: {
            color: "rgba(60, 74, 100, 0.3)",
            borderRadius: [4, 4, 0, 0],
          },
          data: repairTimeData,
        },
        {
          name: "电站停运次数",
          type: "line",
          yAxisIndex: 1,
          smooth: false,
          symbol: "circle",
          symbolSize: 6,
          itemStyle: {
            color: "#FFBF00",
          },
          lineStyle: {
            width: 2,
            color: "#FFBF00",
          },
          data: stationDowntimeData,
        },
        {
          name: "影响充放次数",
          type: "line",
          yAxisIndex: 1,
          smooth: false,
          symbol: "circle",
          symbolSize: 6,
          itemStyle: {
            color: "#38A169",
          },
          lineStyle: {
            width: 2,
            color: "#38A169",
          },
          data: affectedChargeData,
        },
      ],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          crossStyle: {
            color: "#999",
          },
        },
        backgroundColor: "rgba(0,0,0,0.8)",
        borderColor: "#334155",
        textStyle: {
          color: "#e2e8f0",
        },
        formatter: function (params) {
          let tooltipText = params[0].name + "<br/>";
          params.forEach(function (item) {
            tooltipText += item.marker + item.seriesName + ": " + item.value;
            if (item.seriesName === "故障修复时间") {
              tooltipText += " 小时<br/>";
            } else {
              tooltipText += " 次<br/>";
            }
          });
          return tooltipText;
        },
      },
    };
  } else {
    // 其他故障类型的柱状图配置
    const chartConfig = {
      软件故障: {
        title: "软件故障 - 故障细分统计",
        getTotal: (data) => {
          const total = Object.values(data?.segmentCount || {}).reduce(
            (sum, count) => sum + count,
            0
          );
          return `软件故障记录总数: ${total}个`;
        },
        getCategories: (data) => Object.keys(data?.segmentCount || {}),
        getData: (data) => Object.values(data?.segmentCount || {}),
        color: ["#5A8DFF", "#2A5FFF"],
      },
      硬件故障: {
        title: "硬件故障 - 故障细分统计",
        getTotal: (data) => {
          const total = Object.values(data?.segmentCount || {}).reduce(
            (sum, count) => sum + count,
            0
          );
          return `硬件故障记录总数: ${total}个`;
        },
        getCategories: (data) => Object.keys(data?.segmentCount || {}),
        getData: (data) => Object.values(data?.segmentCount || {}),
        color: ["#4fd1c5", "#2c7a7b"],
      },
      技术整改: {
        title: "技术整改 - 故障细分统计",
        getTotal: (data) => {
          const total = Object.values(data?.segmentCount || {}).reduce(
            (sum, count) => sum + count,
            0
          );
          return `技术整改记录总数: ${total}个`;
        },
        getCategories: (data) => Object.keys(data?.segmentCount || {}),
        getData: (data) => Object.values(data?.segmentCount || {}),
        color: ["#5A8DFF", "#2A5FFF"],
      },
      停电整改: {
        title: "停电整改 - 故障细分统计",
        getTotal: (data) => {
          const total = Object.values(data?.segmentCount || {}).reduce(
            (sum, count) => sum + count,
            0
          );
          return `停电整改记录总数: ${total}个`;
        },
        getCategories: (data) => Object.keys(data?.segmentCount || {}),
        getData: (data) => Object.values(data?.segmentCount || {}),
        color: ["#4fd1c5", "#2c7a7b"],
      },
    };

    const selectedData = chartConfig[faultType];
    const faultData = chartData.value.find(
      (item) => item.faultType === faultType
    );
    option = {
      title: [
        {
          text: selectedData.title,
          left: "5%",
          top: "3%",
          textStyle: {
            color: "#e2e8f0",
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        {
          text: selectedData.getTotal(faultData),
          right: "5%",
          top: "3%",
          textStyle: {
            color: "#94a3b8",
            fontSize: 12,
          },
        },
      ],
      grid: {
        left: "5%",
        right: "5%",
        bottom: "30",
        top: "20%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: selectedData.getCategories(faultData),
        axisLine: {
          lineStyle: {
            color: "#475569",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: "#94a3b8",
          fontSize: 12,
          margin: 15,
          interval: 0,
          // formatter: function (params) {
          //   // 两个字后换行
          //   return params
          //     .split("")
          //     .map((char, index) => {
          //       if ((index + 1) % 2 === 0) {
          //         return char + "\n";
          //       }
          //       return char;
          //     })
          //     .join("");
          // },
        },
      },
      yAxis: {
        type: "value",
        min: 0,
        max: 5,
        axisLine: {
          show: true,
          lineStyle: {
            color: "#475569",
          },
        },
        axisLabel: {
          color: "#94a3b8",
        },
        splitLine: {
          lineStyle: {
            color: "#334155",
            type: "dotted",
          },
        },
      },
      series: [
        {
          name: "故障数",
          type: "bar",
          barWidth: "30",
          // barGap: "30",
          // barCategoryGap: "30",
          showBackground: true,
          backgroundStyle: {
            color: "rgba(60, 74, 100, 0.3)",
            borderRadius: [4, 4, 0, 0],
          },
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: selectedData.color[0] },
              { offset: 1, color: selectedData.color[1] },
            ]),
            borderRadius: [4, 4, 0, 0],
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: selectedData.color[0] },
                { offset: 1, color: selectedData.color[1] },
              ]),
            },
          },
          data: selectedData.getData(faultData),
        },
      ],
      dataZoom: [
        {
          type: "slider",
          show: true,
          xAxisIndex: [0, 1],
          start: 0,
          // end: 40,
          endValue: 5,
          height: 10,
          bottom: "10",
        },
      ],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        backgroundColor: "rgba(0,0,0,0.7)",
        borderColor: "#334155",
        textStyle: {
          color: "#e2e8f0",
        },
      },
    };
  }

  barChart.setOption(option, true);
};

// 初始化环形图
const initCircleCharts = () => {
  // 清空之前的图表实例
  circleCharts.value.forEach((chart) => {
    chart && chart.dispose();
  });
  circleCharts.value = [];

  // 动态初始化每个环形图
  chartData.value.forEach((item, index) => {
    if (chartRefs.value[index]) {
      const ratio = parseFloat(item.ratio.replace("%", ""));
      const chart = echarts.init(chartRefs.value[index]);

      // 根据不同故障类型设置不同颜色
      const colorMap = {
        软件故障: ["#4299e1", "#1e3a5f"],
        硬件故障: ["#4fd1c5", "#1e4e4a"],
        用户停电: ["#9f7aea", "#2e2246"],
        技术整改: ["#5A8DFF", "#2A5FFF"],
        停电整改: ["#4fd1c5", "#2c7a7b"],
      };

      // 如果是新的故障类型，使用默认颜色
      const colors = colorMap[item.faultType] || ["#64748b", "#334155"];

      const option = {
        series: [
          {
            type: "pie",
            radius: ["70%", "90%"],
            avoidLabelOverlap: false,
            silent: false,
            cursor: "pointer",
            label: {
              show: false,
            },
            emphasis: {
              scale: true,
              scaleSize: 5,
            },
            data: [
              {
                value: ratio,
                name: item.faultType,
                itemStyle: { color: colors[0] },
              },
              {
                value: 100 - ratio,
                name: "其他",
                itemStyle: { color: colors[1] },
              },
            ],
          },
        ],
      };

      chart.setOption(option);
      circleCharts.value[index] = chart;
    }
  });
};

// 处理图表项点击事件
const handleChartItemClick = (faultType, index) => {
  currentFaultType.value = faultType;
  updateBarChart(faultType);
  animateValue(index, faultType);
};
// 添加数值动画效果
const animateValue = (index, faultType) => {
  const chartValues = document.querySelectorAll(".chartValue");
  if (chartValues && chartValues.length > index) {
    chartValues.forEach((el) => {
      el.style.transform = "translate(-50%, -50%)";
      el.style.fontSize = "";
      el.style.color = "#e2e8f0";
      el.style.transition = "all 0.3s";
    });

    // 选中数值样式
    const selectedValue = chartValues[index];
    selectedValue.style.transform = "translate(-50%, -50%) scale(1.2)";
    const colorMap = {
      软件故障: "#4299e1",
      硬件故障: "#4fd1c5",
      用户停电: "#9f7aea",
      技术整改: "#5A8DFF",
      停电整改: "#4fd1c5",
    };
    // 如果是新的故障类型，使用默认颜色
    const color = colorMap[faultType] || "#64748b";
    selectedValue.style.color = color;
    selectedValue.style.fontWeight = "bold";
  }
};

// 初始化柱状图
const initBarChart = () => {
  if (barChartRef.value) {
    barChart = echarts.init(barChartRef.value);
    // 默认选中第一个故障类型
    if (chartData.value.length > 0) {
      currentFaultType.value = chartData.value[0].faultType;
      updateBarChart(chartData.value[0].faultType);
      animateValue(0, chartData.value[0].faultType);
    }
  }
};

const handleResize = () => {
  circleCharts.value.forEach((chart) => {
    chart && chart.resize();
  });
  barChart && barChart.resize();
};
const loading = ref(false);
const outageDashboardData = async () => {
  const params = {
    planShutdown: props.pageType === "Unplanned" ? 0 : 1,
    dashboardStartDate: dateRange.value[0],
    dashboardEndDate: dateRange.value[1],
    dashboardType: "1", // 1：故障类别分析 2：故障归属分析 3：异常趋势分析-年报 4：异常趋势分析-月报
  };
  loading.value = true;
  const res = await $api.faultDealDashboard(1, params);
  loading.value = false;
  if (res.code === 0 && res.data?.faultDealTypeChildDtoList) {
    chartData.value = res.data.faultDealTypeChildDtoList;
  } else {
    chartData.value = [];
    // 当数据为空时，清空柱状图
    if (barChart) {
      barChart.dispose();
      barChart = null;
    }
    currentFaultType.value = "";
  }
  await nextTick();
  initCircleCharts();
  if (chartData.value.length > 0) {
    initBarChart();
  }
};
const handleReset = async () => {
  dateRange.value = getDefaultDateRange();
  await outageDashboardData();
};
onMounted(async () => {
  await outageDashboardData();
  initCircleCharts();
  initBarChart();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  circleCharts.value.forEach((chart) => {
    chart && chart.dispose();
  });
  barChart && barChart.dispose();
});
</script>

<style scoped lang="less">
.failureAnalysis {
  width: 500px;
  height: 480px;
  padding: 0 12px;
  background: #141414;
  border-radius: 4px;
  border: 1px solid #334155;
  color: #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .titleBar {
    flex-shrink: 0;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #334155;
    color: #e2e8f0;
    position: relative;
    flex-shrink: 0;

    .dateRange {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .circleCharts {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 10px 0;
    width: 100%;
    height: 140px;
    flex-shrink: 0;
    margin-top: 15px;
    .chartItem {
      position: relative;
      width: 30%;
      padding-top: 30%;
      height: 0;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: scale(1.05);
      }

      &.active {
        transform: scale(1.1);

        .chartTitle {
          color: #e2e8f0;
          font-weight: bold;
        }
      }

      .chartContainer {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }

      .chartTitle {
        position: absolute;
        top: 35%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        text-align: center;
        font-size: clamp(10px, 1.5vw, 14px);
        color: #94a3b8;
        white-space: nowrap;
        transition: all 0.3s ease;
      }

      .chartValue {
        position: absolute;
        top: 60%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        text-align: center;
        font-size: clamp(14px, 2.5vw, 24px);
        font-weight: bold;
        color: #e2e8f0;
        transition: all 0.3s;
      }
    }
  }

  .barChartContainer {
    flex: 1;
    min-height: 0;
    padding-top: 10px;
    width: 100%;

    .chartInstance {
      width: 100%;
      height: 100%;
    }
  }
  .noData {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    .noDataText {
      font-size: 14px;
      color: #94a3b8;
    }
  }
}
.ant-picker {
  width: 235px;
}
</style>
